package cn.edu.jxau.test;

import java.util.ArrayList;
import java.util.List;

public class UndirectedGraph {

    public static void main(String[] args) {
        
        UndirectedGraph g = new UndirectedGraph(8);
        g.addEdge(new Edge(4,5,0.35));
        g.addEdge(new Edge(4,7,0.37));
        g.addEdge(new Edge(5,7,0.28));
        g.addEdge(new Edge(0,7,0.16));
        g.addEdge(new Edge(1,5,0.32));
        g.addEdge(new Edge(0,4,0.38));
        g.addEdge(new Edge(2,3,0.17));
        g.addEdge(new Edge(1,7,0.19));
        g.addEdge(new Edge(0,2,0.26));
        g.addEdge(new Edge(1,2,0.36));
        g.addEdge(new Edge(1,3,0.29));
        g.addEdge(new Edge(2,7,0.34));
        g.addEdge(new Edge(6,2,0.40));
        g.addEdge(new Edge(3,6,0.52));
        g.addEdge(new Edge(6,0,0.58));
        g.addEdge(new Edge(6,4,0.93));
        System.out.println(g);
    }

    /**
     * 顶点数
     */
    private final int v;

    /**
     * 边数
     */
    private int e;

    /**
     * 邻接表
     */
    private List<Edge>[] adj;

    public UndirectedGraph(int v) {
        this.v = v;
        adj = new List[v];
        for (int i = 0; i < adj.length; i++) {
            adj[i] = new ArrayList<>();
        }
    }

    public int v() {
        return v;
    }

    public int e() {
        return e;
    }

    public void addEdge(Edge edge) {

        int v = edge.either();
        int w = edge.other(v);
        adj[v].add(edge);
        adj[w].add(edge);
        this.e++;
    }

    public Iterable<Edge> adj(int v) {
        return adj[v];
    }

    public Iterable<Edge> edges() {

        List<Edge> list = new ArrayList<>();
        for (int i = 0; i < v; i++) {
            for (Edge edge : adj[i]) {
                list.add(edge);
            }
        }
        return list;
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder();
        builder.append("v=").append(v).append("\t").append("e=").append(e).append("\n");
        for (int i = 0; i < v; i++) {
            builder.append(i).append(":\t");
            for (Edge edge : adj[i]) {
                System.out.println(edge);
                builder.append(edge.other(i)).append("(").append(edge.weight()).append(")\t");
            }
            builder.append("\n");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }
}
